package org.dromara.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StreamUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.tenant.helper.TenantHelper;
import org.dromara.system.api.domain.bo.RemoteMessageBo;
import org.dromara.system.domain.SysMessage;
import org.dromara.system.domain.SysUser;
import org.dromara.system.domain.bo.SysMessageBo;
import org.dromara.system.domain.vo.SysMessageVo;
import org.dromara.system.mapper.SysMessageMapper;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.system.service.ISysMessageService;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 系统管理-消息通知Service业务层处理
 *
 * @author LionLi
 * @date 2024-03-28
 */
@RequiredArgsConstructor
@Service
@Log4j2
public class SysMessageServiceImpl implements ISysMessageService {

    private final SysMessageMapper baseMapper;
    private final SysUserMapper sysUserMapper;

    /**
     * 查询系统管理-消息通知
     */
    @Override
    public SysMessageVo queryById(String id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询系统管理-消息通知列表
     */
    @Override
    public TableDataInfo<SysMessageVo> queryPageList(SysMessageBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysMessage> lqw = buildQueryWrapper(bo);
        Page<SysMessageVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询系统管理-消息通知列表
     */
    @Override
    public List<SysMessageVo> queryList(SysMessageBo bo) {
        LambdaQueryWrapper<SysMessage> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysMessage> buildQueryWrapper(SysMessageBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysMessage> lqw = Wrappers.lambdaQuery();
        //开始时间,结束时间,接收人id
        lqw.eq(SysMessage::getRecordId, LoginHelper.getLoginUser().getUserId());
        lqw.between(params.get("beginTime") != null && params.get("endTime") != null,
                SysMessage::getCreateTime, params.get("beginTime"), params.get("endTime"));
        lqw.eq(bo.getStatus() != null, SysMessage::getStatus, bo.getStatus());
        lqw.like(StringUtils.isNotEmpty(bo.getMessageContent()),SysMessage::getMessageContent, bo.getMessageContent())
                .orderByAsc(SysMessage::getStatus)
        .orderByDesc(SysMessage::getReadTime);
        return lqw;
    }

    /**
     * 新增系统管理-消息通知
     */
    @Override
    public Boolean insertByBo(SysMessageBo bo)  {
        checkBoParam(bo);
        SysMessage add = MapstructUtils.convert(bo, SysMessage.class);
        add.setSendId(LoginHelper.getLoginUser().getUserId());
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    private void checkBoParam(SysMessageBo bo)  {
        if (ObjectUtil.isNull(bo) ) {
            throw new ServiceException("对象不能为空");
        }
        if (bo.getRecordId() == null) {
            // 所有条件均满足，此处可以安全地使用这两个字段
            throw new ServiceException("消息接收者id不能为空");
        }

    }

    /**
     * 修改系统管理-消息通知
     */
    @Override
    public Boolean updateByBo(SysMessageBo bo) {
        SysMessage update = MapstructUtils.convert(bo, SysMessage.class);
        update.setReadTime(new Date());
        update.setStatus("1");
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 根据id删除通知消息
     *
     * @param id
     * @return
     */
    @Override
    public Boolean deleteWithValidById(Long id) {
          return baseMapper.deleteById(id) > 0;
    }

    /**
     * 当前登入人消息全部已读
     *
     * @return
     */
    @Override
    public Boolean readAll() {
        LambdaUpdateWrapper<SysMessage> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SysMessage::getRecordId, LoginHelper.getLoginUser().getUserId()).
                eq(SysMessage::getStatus, "0").
                set(SysMessage::getReadTime, new Date())
                .set(SysMessage::getStatus, "1");
        return baseMapper.update(updateWrapper) > 0;
    }

    @Override
    public void insertBatchByBo(List<RemoteMessageBo> handlerMessageList) {
        if (CollUtil.isEmpty(handlerMessageList)) {
            return;
        }
        List<SysMessage> list = BeanUtil.copyToList(handlerMessageList, SysMessage.class);
        Set<Long> userIds = list.stream().map(SysMessage::getRecordId).filter(Objects::nonNull).collect(Collectors.toSet());
        // 通过接收人查询对应的租户id
        Map<Long, String> tenantIdMap = TenantHelper.ignore(() -> {
            List<SysUser> sysUsers = this.sysUserMapper.selectBatchIds(userIds);
            return StreamUtils.toMap(sysUsers, SysUser::getUserId, SysUser::getTenantId);
        });

        list.forEach(sysMessage -> sysMessage.setTenantId(tenantIdMap.getOrDefault(sysMessage.getRecordId(), "")));
        baseMapper.insertBatch(list);
    }
}
